#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "object.h"
#include "eg.h"
#include "wall.h"
#include "snake.h"
#include "interection.h"
#include <math.h>
#include <QtGui>
#include <Qlist>


void MainWindow::keyPressEvent(QKeyEvent * event){
    //Object * object = dynamic_cast<Object*> (*scene.items().begin());

    QList<QGraphicsItem *>::iterator i;
    for(i = scene.items().begin();i != scene.items().end() ;i++) if ( ((Object *)(* i)) -> get_type () == 0 )
        break;

    if (( (Object *)(* i)) -> get_type () == 0)
        ((Snake *)(*i)) -> turn_arrow (event->key());
}

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        scene(),
        view(&scene)
{
    ui->setupUi(this);

    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

    scene.setSceneRect(-300, -300, 600, 600);

    scene.setItemIndexMethod(QGraphicsScene::NoIndex);

    scene.addItem(new Wall(-50 , 50 , 16 , 48 , 67));
    scene.addItem(new Wall(60 , 40 , 16 , 34 , 17));
    Eg * mama = new Eg(0);
    new Snake(0 , 0 , mama);
    scene.addItem(mama);
    scene.addItem(new Eg(0));
    scene.addItem(new Eg(0));
    QList<QGraphicsItem *>::iterator i = scene.items().begin() , ai = scene.items().begin();

    while ( i != scene.items().end() ){
        while ( ai != scene.items().end() ){
            // Interaction ( ((Object *)(* i)) , ((Object *)(* ai)) );
            ai ++;
        }
        i ++;
        ai = i;
    }
    ai = scene.items().begin();
    i = scene.items().begin();


    this->setCentralWidget(&view);

    view.setRenderHint(QPainter::Antialiasing);
    view.setBackgroundBrush(QPixmap(":/images/cheese.jpg"));

    view.setCacheMode(QGraphicsView::CacheBackground);
    view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
    view.setDragMode(QGraphicsView::ScrollHandDrag);

    QObject::connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance()));
    timer.start(1000 / 33);
}

MainWindow::~MainWindow()
{
    delete ui;
}
